<script setup lang="ts">
// 生意参谋-市场-搜索词分析-相关词分析-一键转化（生成标题功能）

import {PlusOutlined} from "@ant-design/icons-vue";
import {message} from "ant-design-vue";
import {getCurrentInstance} from "vue";
import BaseApp from "~/contentScripts/views/sycm/baseApp.vue";
import TitleGeneration from "~/contentScripts/views/sycm/search_analyze/TitleGeneration.vue";
import User from "~/contentScripts/views/tao/list/components/user.vue";
import {isLogin} from "~/logic";
import SYCM from "~/utils/ali/sycm";
import HighlightOutlined from "@ant-design/icons-vue/HighlightOutlined";

const loading = ref(false);
const loginVisible = ref(false);
const data = ref([]);
const activeKey = ref('relatedWord');
const columns = ref<any[]>([]);
const dataSource = ref<any[]>([]);
const visible = ref(false);
const __option = getCurrentInstance()?.appContext.provides.option;
const handle = async () => {
  if (isLogin({
    emit: () => {
      loginVisible.value = true
    }
  }, __option)) {
    loading.value = true;
    let data = await SYCM.getInternalFiberData('div.oui-card > div.oui-card-content div.oui-card-content', 'memoizedProps.children._owner.memoizedProps.originalTableData');
    if (data == null) {
      loading.value = false;
      return message.error('获取数据失败，请重试！');
    }
    if (data.length === 0) {
      loading.value = false;
      return message.warning('无需要转换的数据！');
    }
    let switchData = await SYCM.getInternalFiberData('.oui-card-header-item .oui-tab-switch', 'memoizedProps.children[0]._owner.memoizedProps');
    if (switchData == null) {
      loading.value = false;
      return message.error('获取数据失败，请重试！');
    }
    activeKey.value = switchData.activeTab;
    SYCM.assignData(data.data);
    console.log(data.data, switchData.activeTab);
    if (switchData.activeTab === 'relatedWord') {
      data.data.map(item => {
        item.analysisKeyword = data.params.keyword;
        let dateRange = data.params.dateRange.split('|');
        if (dateRange.length === 2) {
          if (dateRange[0] === dateRange[1]) {
            item.date = dateRange[0];
          } else {
            item.date = dateRange[0] + '~' + dateRange[1];
          }
        } else {
          item.date = dateRange[0];
        }
        // 计算买家数
        item.buyerNumber = Math.round(item.clickHits_tran * item.payConvRate);
        // 计算客单价
        item.customerUnitPrice = (item.tradeIndex_tran / item.buyerNumber).toFixed(2);
        // 商品平均搜索人数 搜索人数/商品数
        item.productSearchNumber = (item.seIpvUvHits_tran / item.onlineGoodsCnt).toFixed(2);
        // 商品平均交易金额 交易金额/商品数
        item.productTradeAmount = (item.tradeIndex_tran / item.onlineGoodsCnt).toFixed(2);
        // 机会值=((搜索人数*支付转化率)/在线商品数)*1000，机会值越大，关键词获取流量和转化的能力越高
        item.opportunityValue = (((item.seIpvUvHits_tran * item.payConvRate) / item.onlineGoodsCnt) * 1000).toFixed(2);
      });
      columns.value = [
        {
          title: '搜索词',
          dataIndex: 'keyword',
          width: 140,
          ellipsis: true,
          fixed: 'left',
          sorter: (a: any, b: any) => a.keyword.length - b.keyword.length,
        },
        {
          title: '分析词',
          dataIndex: 'analysisKeyword',
          width: 140,
          ellipsis: true,
          fixed: 'left',
          sorter: (a: any, b: any) => a.analysisKeyword.length - b.analysisKeyword.length,
        },
        {
          title: '日期',
          dataIndex: 'date',
          width: 200,
          ellipsis: true,
          fixed: 'left',
          sorter: (a: any, b: any) => a.date.length - b.date.length,
        }, {
          title: '搜索人数',
          dataIndex: 'seIpvUvHits_tran',
          width: 100,
          align: 'right',
          calc: true,
          sorter: (a: any, b: any) => a.seIpvUvHits_tran - b.seIpvUvHits_tran,
        },
        {
          title: '搜索次数',
          dataIndex: 'sePvIndex_tran',
          width: 100,
          align: 'right',
          calc: true,
          sorter: (a: any, b: any) => a.sePvIndex_tran - b.sePvIndex_tran,
        },
        {
          title: '点击率',
          dataIndex: 'clickRate',
          width: 100,
          dataType: 'customRender',
          align: 'center',
          calc: true,
          sorter: (a: any, b: any) => a.clickRate - b.clickRate,
          render: (text: any, record: any, index: any) => {
            if (isNaN(text)){
              return '--';
            }
            return (record.clickRate * 100).toFixed(2) + '%';
          }
        },
        {
          title: '点击次数',
          dataIndex: 'clickHits_tran',
          width: 100,
          align: 'right',
          calc: true,
          sorter: (a: any, b: any) => a.clickHits_tran - b.clickHits_tran,
        },
        {
          title: '交易金额',
          dataIndex: 'tradeIndex_tran',
          width: 100,
          align: 'right',
          calc: true,
          sorter: (a: any, b: any) => a.tradeIndex_tran - b.tradeIndex_tran,
        },
        {
          title: '支付转化率',
          dataIndex: 'payConvRate',
          width: 120,
          sorter: (a: any, b: any) => a.payConvRate - b.payConvRate,
          align: 'center',
          dataType: 'customRender',
          calc: true,
          render: (text: any, record: any, index: any) => {
            if (isNaN(text)) {
              return '--';
            }
            return (record.payConvRate * 100).toFixed(2) + '%';
          }
        },
        {
          title: '在线商品数',
          dataIndex: 'onlineGoodsCnt',
          width: 120,
          align: 'right',
          calc: true,
          sorter: (a: any, b: any) => a.onlineGoodsCnt - b.onlineGoodsCnt,
        },
        {
          title: '商城点击占比',
          dataIndex: 'tmClickRatio',
          width: 140,
          sorter: (a: any, b: any) => a.tmClickRatio - b.tmClickRatio,
          dataType: 'customRender',
          calc: true,
          align: 'center',
          render: (text: any, record: any, index: any) => {
            if (isNaN(text)) {
              return '--';
            }
            return (record.tmClickRatio * 100).toFixed(2) + '%';
          }
        },
        {
          title: '直通车参考价',
          dataIndex: 'p4pAmt',
          width: 140,
          sorter: (a: any, b: any) => a.p4pAmt - b.p4pAmt,
          dataType: 'customRender',
          align: 'right',
          calc: true,
          render: (text: any, record: any, index: any) => {
            if (typeof record.p4pAmt === 'undefined') {
              return '--';
            }
            return (record.p4pAmt).toFixed(2);
          }
        },
        {
          title: '买家人数',
          dataIndex: 'buyerNumber',
          align: 'right',
          sorter: (a: any, b: any) => a.buyerNumber - b.buyerNumber,
          width: 100,
          calc: true,
          dataType: 'customRender',
          render: (text: any, record: any, index: any) => {
            if (isNaN(text)) {
              return '--';
            }
            return Math.round(text);
          }
        },
        {
          title: '客单价',
          dataIndex: 'customerUnitPrice',
          align: 'right',
          sorter: (a: any, b: any) => a.customerUnitPrice - b.customerUnitPrice,
          width: 100,
          calc: true,
          dataType: 'customRender',
          render: (text: any, record: any, index: any) => {
            if (isNaN(text)) {
              return '--';
            }
            return text;
          }
        },
        {
          title: '搜索人数/商品数',
          dataIndex: 'productSearchNumber',
          align: 'right',
          sorter: (a: any, b: any) => a.productSearchNumber - b.productSearchNumber,
          width: 160,
          calc: true,
          dataType: 'customRender',
          render: (text: any, record: any, index: any) => {
            if (isNaN(text)) {
              return '--';
            }
            return text;
          }
        },
        {
          title: '交易金额/商品数',
          dataIndex: 'productTradeAmount',
          sorter: (a: any, b: any) => a.productTradeAmount - b.productTradeAmount,
          align: 'right',
          calc: true,
          width: 160,
          dataType: 'customRender',
          render: (text: any, record: any, index: any) => {
            if (isNaN(text)) {
              return '--';
            }
            return text;
          }
        },
        {
          title: '机会值',
          dataIndex: 'opportunityValue',
          sorter: (a: any, b: any) => a.opportunityValue - b.opportunityValue,
          align: 'right',
          calc: true,
          width: 100,
          dataType: 'customRender',
          render: (text: any, record: any, index: any) => {
            if (isNaN(text)) {
              return '--';
            }
            return text;
          }
        }
      ];
    } else {
      data.data.map(item => {
        item.analysisKeyword = data.params.keyword;
        let dateRange = data.params.dateRange.split('|');
        if (dateRange.length === 2) {
          if (dateRange[0] === dateRange[1]) {
            item.date = dateRange[0];
          } else {
            item.date = dateRange[0] + '~' + dateRange[1];
          }
        } else {
          item.date = dateRange[0];
        }
        // 计算词均支付人数 = (点击人数 * 词均支付转化率) / 相关词数
        item.avgWordPeoplePaidNumber = Math.round((item.clickHits_tran * item.avgWordPayRate) / item.relSeWordCnt);
      });
      columns.value = [
        {
          title: '搜索词',
          dataIndex: 'keyword',
          width: 140,
          ellipsis: true,
          fixed: 'left',
          sorter: (a: any, b: any) => a.keyword.length - b.keyword.length,
        },
        {
          title: '分析词',
          dataIndex: 'analysisKeyword',
          width: 140,
          ellipsis: true,
          fixed: 'left',
          sorter: (a: any, b: any) => a.analysisKeyword.length - b.analysisKeyword.length,
        },
        {
          title: '日期',
          dataIndex: 'date',
          width: 200,
          ellipsis: true,
          fixed: 'left',
          sorter: (a: any, b: any) => a.date.length - b.date.length,
        }, {
          title: '搜索人数',
          dataIndex: 'seIpvUvHits_tran',
          width: 100,
          align: 'right',
          calc: true,
          sorter: (a: any, b: any) => a.seIpvUvHits_tran - b.seIpvUvHits_tran,
        },
        {
          title: '搜索词数',
          dataIndex: 'relSeWordCnt',
          width: 100,
          align: 'right',
          sorter: (a: any, b: any) => a.relSeWordCnt - b.relSeWordCnt,
        },
        {
          title: '词均点击率',
          dataIndex: 'avgWordClickRate',
          width: 120,
          align: 'center',
          calc: true,
          dataType: 'customRender',
          sorter: (a: any, b: any) => a.avgWordClickRate - b.avgWordClickRate,
          render: (text: any, record: any, index: any) => {
            if (isNaN(text)){
              return '--';
            }
            return (record.avgWordClickRate * 100).toFixed(2) + '%';
          }
        },
        {
          title: '点击人数',
          dataIndex: 'clickHits_tran',
          width: 100,
          align: 'right',
          calc: true,
          sorter: (a: any, b: any) => a.clickHits_tran - b.clickHits_tran,
        },
        {
          title: '词均支付转换率',
          dataIndex: 'avgWordPayRate',
          width: 140,
          dataType: 'customRender',
          align: 'center',
          calc: true,
          sorter: (a: any, b: any) => a.avgWordPayRate - b.avgWordPayRate,
          render: (text: any, record: any, index: any) => {
            if (isNaN(text)){
              return '--';
            }
            return (record.avgWordPayRate * 100).toFixed(2) + '%';
          }
        },
        {
          title: '词均支付人数',
          dataIndex: 'avgWordPeoplePaidNumber',
          width: 140,
          align: 'right',
          calc: true,
          sorter: (a: any, b: any) => a.avgWordPeoplePaidNumber - b.avgWordPeoplePaidNumber,
          dataType: 'customRender',
          render: (text: any, record: any, index: any) => {
            if (isNaN(text)) {
              return '--';
            }
            return Math.round(text);
          }
        },
        {
          title: '直通车参考价',
          dataIndex: 'p4pAmt',
          width: 140,
          sorter: (a: any, b: any) => a.p4pAmt - b.p4pAmt,
          dataType: 'customRender',
          align: 'right',
          calc: true,
          render: (text: any, record: any, index: any) => {
            if (typeof record.p4pAmt === 'undefined') {
              return '--';
            }
            return (record.p4pAmt).toFixed(2);
          }
        },
      ];
    }
    dataSource.value = data.data;
    loading.value = false;
    visible.value = true;
  }
}
const selectedRows = ref([]);
const keywords = ref([]);
</script>

<template>
  <base-app>
    <a-button-group>
      <user style="margin-right: 0;"/>
      <a-button :loading="loading" type="primary" size="small" @click="handle">一键转化/标题生成</a-button>
    </a-button-group>
    <custom-modal title="搜索分析-相关词分析-相关搜索词_标题生成" width="95%" style="top: 20px;"
                  v-model:visible="visible"
    >
      <template #headerRight>
        <s-y-c-m-custom-modal-header-notice/>
      </template>
      <div style="max-height: calc(100vh - 150px);overflow-y: auto;">
        <TitleGeneration :data="dataSource" :columns="columns"/>
        <a-divider/>
        <base-table row-key="keyword" :scroll="{
          y: 500
        }" size="small" v-model:selected-rows="selectedRows" table-name="搜索分析-相关词分析-相关搜索词"
                    :data-source="dataSource"
                    :columns="columns"
        >
          <!--          <template #toolbar>-->
          <!--            &lt;!&ndash;加入标题&ndash;&gt;-->
          <!--            <a-button type="default" size="small" @click="()=>{-->
          <!--              let text = '';-->
          <!--              selectedRows.forEach((item,index)=>{-->
          <!--                if(index===0){-->
          <!--                  text+=item.keyword;-->
          <!--                }else {-->
          <!--                  text+=','+item.keyword;-->
          <!--                }-->
          <!--              });-->
          <!--            }"-->
          <!--            >-->
          <!--              <PlusOutlined class="icon"/>-->
          <!--              加入标题-->
          <!--            </a-button>-->
          <!--          </template>-->
        </base-table>
      </div>
    </custom-modal>
    <user-login-modal v-model:login-visible="loginVisible"/>
  </base-app>
</template>

<style scoped>

</style>
